package com.msh.automatic.android.api.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.RSASSAVerifier;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jwt.SignedJWT;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;

@Slf4j
@Data
@Component
public class JwksUtil {

    RSAKey key;

    @PostConstruct
    public void init() {
        // 你要调用的逻辑
        try (InputStream input = this.getClass().getResourceAsStream("/jwks.json")){
            String config = IoUtil.readUtf8(input);
            JWK jwk = JWK.parse(config);
            this.key = (RSAKey) jwk;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
    public SignedJWT verify(String jwt){
        try {
            SignedJWT signedJWT = SignedJWT.parse(jwt);
            JWSVerifier verifier = new RSASSAVerifier(this.key.toRSAPublicKey());
            if(!signedJWT.verify(verifier)){
                return null;
            }
            if(!DateUtil.isDateTodayOrAfter(signedJWT.getJWTClaimsSet().getExpirationTime())){
                return null;
            }
            return signedJWT;
        } catch (ParseException e) {
            log.error("e",e);
        } catch (JOSEException e) {
            log.error("e",e);
        }
        return null;
    }
}
